package me.sealer.jmx.agent;

import com.sun.jdmk.comm.HtmlAdaptorServer;
import lombok.extern.slf4j.Slf4j;
import me.sealer.jmx.mbean.Hello;

import javax.management.*;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.MalformedURLException;
import java.rmi.registry.LocateRegistry;

/**
 * @author sealer
 * @date 2018/01/22.
 */
@Slf4j
public class HelloRmiAgent {
    public static void main(String[] args) throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException {
        //create mbean server
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        //create object name
        ObjectName helloName = new ObjectName("jmxBean:name=hello");
        //create mbean and register mbean
        mBeanServer.registerMBean(new Hello(), helloName);

        //create adaptor, adaptor is just a form as show mbean. It has no relation to specific mbean.
        HtmlAdaptorServer adaptor  = new HtmlAdaptorServer();
        //create adaptor name
        ObjectName adaptorName = new ObjectName("jmxAdaptor:name=adaptor,port=5050");
        //register adaptor and adaptor name
        mBeanServer.registerMBean(adaptor, adaptorName);
        adaptor.setPort(9999);
        adaptor.start();
        log.debug("....................html server start....................");

        //JMXConnectorServer service
        try {
            //这句话非常重要，不能缺少！注册一个端口，绑定url后，客户端就可以使用rmi通过url方式来连接JMXConnectorServer
            LocateRegistry.createRegistry(8888);
            JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:8888/server");
//            JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:8888/server");
            JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mBeanServer);
            log.debug("....................begin rmi start.....");
            cs.start();
            log.debug("....................rmi start.....");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
